#include "tcp_handle.h"
#include "local/const_attr.h"

TcpHandle::TcpHandle(InterfaceObj* in)
{
    mInterface = in;
    mClient = new TcpClientPort(1024 * 1024);
    mProtocol = new TcpProtocolJson(8 * 1024);
    mClient->SetupRxCallBack([](void* param, const uint8_t* data, int32_t len) {
        TcpHandle* self = (TcpHandle*)param;
        self->mProtocol->PushBuffer(data, len);
    }, this);
}

TcpHandle::~TcpHandle()
{
    if (mClient)
        delete mClient;
    if (mProtocol)
        delete mProtocol;
}

bool TcpHandle::Open()
{
    if (mPushServerList.empty())
        return false;
    return mClient->Open(mPushServerList[0].ip, mPushServerList[0].port);
}

void TcpHandle::Close()
{
    mClient->Close();
}

void TcpHandle::Reopen()
{
    Close();
    Open();
}

void TcpHandle::Start()
{
    mClient->Start();
}

void TcpHandle::Stop()
{
    mClient->Stop();
}

void TcpHandle::SetRecvCallBack(PackageDataCallBack cb, void* param)
{
    mProtocol->AddCallBack(cb, param);
}

int TcpHandle::PushRawData(const uint8_t* data, int len)
{
    const char* gTailBuf = "#\t#";
    int ret = -1;
    if (len > 0 && mClient != nullptr) {
        FLOGD("in function send TcpHandle : %s, data %s", __FUNCTION__, (char*)data);
        mClient->Send(data, len);
        mClient->Send((const uint8_t*)gTailBuf, strlen(gTailBuf));
    }
    return ret;
}

int TcpHandle::SendIdentify()
{
    char buf[512];
    const char* msg10001Format = "{\"infoType\": 10001, \"connectionType\" : 1, \"data\" : {\"token\":\"\", \"sn\" : \"%s\"}}";
	snprintf(buf, sizeof(buf), msg10001Format, CONST_ATTR->GetSn().c_str());
    return PushRawData((const uint8_t*)buf, strlen(buf));
}

bool TcpHandle::IsOpen()
{
    return mClient->IsOpened();
}